const Router = require("koa-router")
const ResBody = require("../struct/ResBody")
const { Room, Floor, User, Building } = require("../model")
const router = new Router()

router.get("/getRoomsInfoList", async context => {
  const queryInfo = context.request.query
  let roomListyInfo = []
  if (queryInfo.floorId) {
    roomListyInfo = await Room.findAll({ where: { floorId: queryInfo.floorId } })
  } else if (queryInfo.buildingId && !queryInfo.layer) {
    roomListyInfo = await Room.findAll({ where: { buildingId: queryInfo.buildingId } })
  } else if (queryInfo.buildingId && queryInfo.layer) {
    const floorInfo = await Floor.findOne({ where: { buildingId: queryInfo.buildingId, layer: queryInfo.layer } })
    roomListyInfo = await Room.findAll({ where: { floorId: floorInfo.id } })
  } else {
    roomListyInfo = await Room.findAll()
  }
  // 计算楼栋里面每个房间当前的已经入住的人数
  for (let item in roomListyInfo) {
    const roomInfo = roomListyInfo[item]
    const roomId = roomInfo.id
    const currentPeopleNum = await User.count({ where: { roomId } })
    roomInfo.dataValues.currentPeopleNum = currentPeopleNum
    roomInfo.dataValues.isFull = Boolean(currentPeopleNum === roomInfo.peopleNum)
  }
  context.body = new ResBody({
    data: { rooms: roomListyInfo }
  })
})

router.get("/getRoomInfo", async context => {
  const { roomId } = context.request.query
  const roomInfo = await Room.findOne({
    where: { id: roomId },
    include: [{ model: Floor }, { model: Building }, { model: User }]
  })
  context.body = new ResBody({ data: roomInfo })
})

router.post("/updateInfo", async context => {
  const { roomId } = context.request.body
  const room = await Room.findOne({ where: { id: roomId } })
  const reqBody = context.request.body
  for (let key in reqBody) {
    if (
      Object.hasOwnProperty.call(room.toJSON(), key) &&
      ![undefined, null, ""].includes(reqBody[key])
    ) {
      room[key] = reqBody[key]
    }
  }
  context.body = new ResBody({ data: await room.save() })
})

module.exports = router.routes()
